/*
 * @Author: 码上talk|RC
 * @Date: 2020-06-09 23:23:29
 * @LastEditTime: 2021-01-15 15:35:40
 * @LastEditors: 码上talk|RC
 * @Description: 
 * @FilePath: /tacomall-admin/src/middleware/beforeEach.js
 * @Just do what I think it is right
 */
/* eslint-disable */

import { router } from '@/router'
import { session } from '@/libs/session'
import { store } from '@/store'
import dynamicRoutes from '@/router/routes/dynamic'


router.beforeEach(async (to, from, next) => {
    if (!store.state.sys.isDaynamicRoutesReady) {
        if (!session.get() && to.path === '/login') {
            next()
            return
        }
        await store.dispatch('sys/queryRules', {})
        next({
            ...to,
            replace: true
        })
    } else {
        if (!to.matched.length) {
            let routes = []
            dynamicRoutes.forEach(i => {
                i.children & i.children.forEach(j => {
                    routes.push({
                        path: j.path
                    })
                })
            })
            if (routes.map(i => i.path).includes(to.path)) {
                next({ path: '/403' })
                return
            }
            next({ path: '/404', query: { redirect: to.fullPath } })
            return
        }
        if (to.matched.some(record => record.meta.requiresAuth)) {
            if (!session.get()) {
                next({
                    path: '/login',
                    query: { redirect: to.fullPath }
                })
            } else {
                next()
            }
        } else {
            next()
        }
    }
})